package com.engineering.elink.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.engineering.elink.co.PersonDynamicCo;
import com.engineering.elink.co.PersonMuitlTypeCo;
import com.engineering.elink.co.PersonUpdateCo;
import com.engineering.elink.common.Constant;
import com.engineering.elink.common.ResultType;
import com.engineering.elink.domain.User;
import com.engineering.elink.service.CookieService;
import com.engineering.elink.service.PersonDynamicService;
import com.engineering.elink.service.PersonService;
import com.engineering.elink.service.UserService;
import com.engineering.elink.util.MapConvert;
import com.engineering.elink.util.token.TokenGenerator;
import com.engineering.elink.util.verify.CodeImageGenerator;
import com.engineering.elink.util.verify.VerifyCodeUtils;

@RestController
@RequestMapping("/api/person")
@Api(value = "个人接口")
public class PersonController {
	@Autowired
	private CookieService cookieService;
	@Autowired
	private UserService userService;
	@Autowired
	private PersonService personService;
	@Autowired
	private PersonDynamicService personDynamicService;
	/**
	 * 个人登录流程一 获取个人登录验证码
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/personLoginWithVerifyCode", method = RequestMethod.GET)
	@ApiOperation(value = "个人登录流程一：获取验证码")
	public Map<String, Object> personLoginWithVerifyCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String verifyToken = TokenGenerator.getToken();
		String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
		System.out.println("#####验证码为#####"+verifyCode);
		// 存入验证码缓存中
		userService.generateVerifyCode(Constant.redisCommonCache, verifyToken, verifyCode, Constant.personLoginCacheOneStepValidTime);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("img", CodeImageGenerator.generateBase64Image(verifyCode));
		map.put("verifyToken", verifyToken + "," + Constant.verifyCodeForTempValidTime);
		return MapConvert.getMap(ResultType.SUCCESS, map);
	}

	/**
	 * 个人登录流程二
	 * 
	 * @param account
	 * @param passwd
	 * @param verifyCode
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/personLogin", method = RequestMethod.POST)
	@ApiOperation(value = "个人登录流程二：提交帐号密码")
	public Map<String, Object> personLogin(
			@ApiParam(value = "账号", required = true) @RequestParam(value = "account", required = true) String account,
			@ApiParam(value = "密码", required = true) @RequestParam(value = "passwd", required = true) String passwd, 
			@ApiParam(value = "验证码", required = true) @RequestParam(value = "verifyCode", required = true) String verifyCode,
			@ApiParam(value = "令牌", required = true) @RequestParam(value = "verifyToken", required = true) String verifyToken,
			HttpServletRequest request, HttpServletResponse response) {
		if (userService.checkVerifyCode(Constant.redisCommonCache, verifyToken, verifyCode)) {
			Map<String, Object> map = personService.login(account, passwd);
			if (map != null) {
				String newAuthToken = (userService.refreshAuthToken(((User) map.get("user")).getUserId()));
				String authToken = (newAuthToken == null ? (String) map.get("authToken") : newAuthToken);
				Map<String, Object> authMap = new HashMap<String, Object>();
				authMap.put("seed", (String) map.get("seed") + "," + Constant.verifyCodeForLoginValidTime);
				authMap.put("authToken", authToken + "," + Constant.verifyCodeForLoginValidTime);
				return MapConvert.getMap(ResultType.SUCCESS, authMap);
			} else {
				return MapConvert.getMap(ResultType.PASSWORD_ERROR);
			}
		} else {
			return MapConvert.getMap(ResultType.TOKEN_ERROR);
		}
	}

	/**
	 * 个人注册流程一 获取个人注册验证码
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/personRegWithVerifyCode", method = RequestMethod.GET)
	@ApiOperation(value = "个人注册流程一：获取验证码")
	public Map<String, Object> personRegWithVerifyCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 生成随机字串
		String verifyToken = TokenGenerator.getToken();
		String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
		// 存入验证码缓存中
		personService.personRegWithVerifyCode(verifyToken, verifyCode);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("img", CodeImageGenerator.generateBase64Image(verifyCode));
		map.put("verifyToken", verifyToken + "," + Constant.verifyCodeForTempValidTime);
		return MapConvert.getMap(ResultType.SUCCESS, map);
	}

	/**
	 * 个人注册流程二 发送手机短信验证码
	 * 
	 * @param verifyCode
	 * @param phone
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/personRegWithSendPhoneCode", method = RequestMethod.POST)
	@ApiOperation(value = "个人注册流程二：发送短信验证码")
	public Map<String, Object> sendPhoneVerifyCode(
			@ApiParam(value = "验证码", required = true) @RequestParam(value = "verifyCode", required = true) String verifyCode,
			@ApiParam(value = "手机号", required = true) @RequestParam(value = "phone", required = true) String phone,
			@ApiParam(value = "令牌", required = true) @RequestParam(value = "verifyToken", required = true) String verifyToken, HttpServletRequest request) {
		if (personService.personRegWithSendPhoneCode(phone, verifyToken, verifyCode)) {
			return MapConvert.getMap(ResultType.SUCCESS);
		}
		return MapConvert.getMap(ResultType.TOKEN_ERROR);

	}

	/**
	 * 个人注册流程三 个人注册
	 * 
	 * @param email
	 * @param phone
	 * @param passwd
	 * @param verifyCode
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/personRegWithBaseInfo", method = RequestMethod.POST)
	@ApiOperation(value = "个人注册流程三：注册信息提交")
	public Map<String, Object> personRegWithBaseInfo(@ApiParam(value = "邮箱", required = true) @RequestParam(value = "email", required = true) String email,
			@ApiParam(value = "手机号", required = true) @RequestParam(value = "phone", required = true) String phone,
			@ApiParam(value = "密码", required = true) @RequestParam(value = "passwd", required = true) String passwd,
			@ApiParam(value = "验证码", required = true) @RequestParam(value = "verifyCode", required = true) String verifyCode,
			@ApiParam(value = "令牌", required = true) @RequestParam(value = "verifyToken", required = true) String verifyToken, HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> map = personService.personRegWithBaseInfo(email, phone, passwd, verifyToken, verifyCode);
		if (map != null) {
			Map<String, Object> authMap = new HashMap<String, Object>();
			authMap.put("seed", (String) map.get("seed") + "," + Constant.verifyCodeForLoginValidTime);
			authMap.put("authToken", (String) map.get("authToken") + "," + Constant.verifyCodeForLoginValidTime);
			return MapConvert.getMap(ResultType.SUCCESS, authMap);
		}
		return MapConvert.getMap(ResultType.TOKEN_ERROR);
	}
	
	/**
	 * 修改个人中心分类(职业状态，职业，专业，工程类目)
	 * @param personMuitlTypeCo
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "modifyPersonMuitlType", method = RequestMethod.POST)
	@ApiOperation(value = " 修改个人中心分类(职业状态，职业，专业，工程类目,百问百答)",httpMethod="POST")
	public Map<String, Object> modifyPersonMuitlType(@ModelAttribute @Valid PersonMuitlTypeCo personMuitlTypeCo,HttpServletRequest request) {
		Map<String,Object> userInfo  = (Map<String, Object>) request.getAttribute("userInfo");
		if (userInfo != null && userInfo.containsKey("userId")) {
			String userId = (String) userInfo.get("userId");
			personMuitlTypeCo.setUserId(userId);
			return MapConvert.getMap(ResultType.SUCCESS, personService.modifyMutilType(personMuitlTypeCo));
		}
		return null;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "getPersonMuitlType", method = RequestMethod.GET)
	@ApiOperation(value = " 获取个人中心分类(职业状态，职业，专业，工程类目,百问百答)",httpMethod="GET")
	public Map<String, Object> getPersonMuitlType(HttpServletRequest request) {
		Map<String,Object> userInfo  = (Map<String, Object>) request.getAttribute("userInfo");
		if (userInfo != null && userInfo.containsKey("userId")) {
			String userId = (String) userInfo.get("userId");
			return MapConvert.getMap(ResultType.SUCCESS, personService.getPersonInfo(userId));
		}
		return null;
	}
	
	/**
	 * 获取个人动态
	 * @param companyDynamicCo
	 * @return
	 */
	@RequestMapping(value = "getPersonDynamicList", method = RequestMethod.GET)
	@ApiOperation(value = " 获取个人动态")
	public Map<String, Object> getPersonDynamicList(@ModelAttribute("PersonDynamicCo") @Valid PersonDynamicCo personDynamicCo) {
		return MapConvert.getMap(ResultType.SUCCESS, personDynamicService.getPersonDynamicList(personDynamicCo));
	}
	/**
	 * 获取个人档案
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "getCurrentPersonInfo", method = RequestMethod.GET)
	@ApiOperation(value = " 获取个人档案")
	public Map<String, Object> getCurrentPersonInfo(HttpServletRequest request) {
		Map<String,Object> userInfo  = (Map<String, Object>) request.getAttribute("userInfo");
		if (userInfo != null && userInfo.containsKey("userId")) {
			String userId = (String) userInfo.get("userId");
			return MapConvert.getMap(ResultType.SUCCESS, personService.getPersonInfo(userId));
		}
		return MapConvert.getMap(ResultType.REQUEST_PARAMS_ERROR);
	}

	/**
	 * 修改个人档案
	 * 
	 * @param personUpdateCo
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "modifyPersonInfo", method = RequestMethod.POST)
	@ApiOperation(value = " 修改个人档案")
	public Map<String, Object> modifyPersonInfo(@ModelAttribute @Valid PersonUpdateCo personUpdateCo,HttpServletRequest request) {
		Map<String,Object> userInfo  = (Map<String, Object>) request.getAttribute("userInfo");
		if (userInfo != null && userInfo.containsKey("userId")) {
			String userId = (String) userInfo.get("userId");
			personUpdateCo.setUserId(userId);
			return MapConvert.getMap(ResultType.SUCCESS, personService.modifyPersonInfo(personUpdateCo));
		}
		return MapConvert.getMap(ResultType.REQUEST_PARAMS_ERROR);
	}


	/**
	 * 获取自己的顶部个人信息
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "getBasePersonInfoByMine", method = RequestMethod.GET)
	@ApiOperation(value = "获取自己的顶部个人信息")
	public Map<String, Object> getBasePersonInfoByMine(HttpServletRequest request) {
		Map<String,Object> userInfo  = (Map<String, Object>) request.getAttribute("userInfo");
		if (userInfo != null && userInfo.containsKey("userId")) {
			String userId = (String) userInfo.get("userId");
			return MapConvert.getMap(ResultType.SUCCESS, personService.getBasePersonInfoByMine(userId));
		}
		return MapConvert.getMap(ResultType.REQUEST_PARAMS_ERROR);
	}

	/**
	 * 获取别人的顶部个人信息
	 * 
	 * @param otherUserId
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "getBasePersonInfoByOther", method = RequestMethod.GET)
	@ApiOperation(value = "获取别人的顶部个人信息")
	public Map<String, Object> getBasePersonInfoByOther(
			@ApiParam(value = "他人userId", required = true) @RequestParam(value = "otherUserId", required = true) String otherUserId, HttpServletRequest request) {
		String userId =null;
		try {
			Map<String,Object> userInfo  = (Map<String, Object>) request.getAttribute("userInfo");
			userId =  userInfo.get("userId").toString();
			return MapConvert.getMap(ResultType.SUCCESS, personService.getBasePersonInfoByOther(userId, otherUserId));
		} catch (Exception e) {
			
		}
		return MapConvert.getMap(ResultType.REQUEST_PARAMS_ERROR);
	}
}
